const DB_NAME = 'fames';
const DB = db.getSiblingDB(DB_NAME);

function ensureCollection(name, jsonSchema) {
  const exists = DB.getCollectionNames().includes(name);
  if (!exists) {
    DB.createCollection(name, {
      validator: { $jsonSchema: jsonSchema },
      validationLevel: 'moderate',
      validationAction: 'error'
    });
    print(`Created collection: ${name}`);
  } else {
    DB.runCommand({
      collMod: name,
      validator: { $jsonSchema: jsonSchema },
      validationLevel: 'moderate',
      validationAction: 'error'
    });
    print(`Updated validator for collection: ${name}`);
  }
}

ensureCollection('reports', {
  bsonType: 'object',
  required: ['activity_ids', 'template_version_code', 'sections', 'status', 'audit'],
  properties: {
    activity_ids: { bsonType: 'array', minItems: 1, items: { bsonType: 'string' } },
    title: { bsonType: 'string' },
    template_version_code: { bsonType: 'string' },
    docx: {
      bsonType: 'object',
      properties: {
        file_url: { bsonType: 'string' },
        generated_at: { bsonType: 'date' },
        generated_by: { bsonType: 'string' }
      }
    },
    pdf: {
      bsonType: 'object',
      properties: {
        file_url: { bsonType: 'string' },
        generated_at: { bsonType: 'date' }
      }
    },
    sections: {
      bsonType: 'array',
      minItems: 1,
      items: {
        bsonType: 'object',
        required: ['section_no', 'section_name', 'level', 'status', 'content'],
        properties: {
          section_no: { bsonType: 'string' },
          section_name: { bsonType: 'string' },
          level: { bsonType: 'int' },
          style: { bsonType: 'string' },
          required: { bsonType: 'bool' },
          status: { enum: ['draft', 'reviewed', 'final'] },
          binding: {
            bsonType: 'object',
            properties: {
              activity_ids: { bsonType: 'array', items: { bsonType: 'string' } },
              activity_fields: { bsonType: 'array', items: { bsonType: 'string' } },
              indicator_item_ids: { bsonType: 'array', items: { bsonType: 'string' } },
              indicator_theme_ids: { bsonType: 'array', items: { bsonType: 'string' } },
              event_ids: { bsonType: 'array', items: { bsonType: 'string' } },
              event_filters: {
                bsonType: 'object',
                properties: {
                  types: { bsonType: 'array', items: { bsonType: 'string' } },
                  date_range: {
                    bsonType: 'object',
                    properties: { start: { bsonType: 'date' }, end: { bsonType: 'date' } }
                  },
                  status: { bsonType: 'array', items: { bsonType: 'string' } }
                }
              },
              computed_metrics: {
                bsonType: 'object',
                properties: {
                  score_total: { bsonType: 'double' },
                  deductions: {
                    bsonType: 'array',
                    items: {
                      bsonType: 'object',
                      required: ['item_id', 'value'],
                      properties: { item_id: { bsonType: 'string' }, value: { bsonType: 'double' } }
                    }
                  },
                  veto_hit: { bsonType: 'bool' }
                }
              }
            }
          },
          content: {
            bsonType: 'object',
            properties: {
              raw_text: { bsonType: 'string' },
              edited_text: { bsonType: 'string' },
              candidates: {
                bsonType: 'array',
                items: {
                  bsonType: 'object',
                  required: ['candidate_id', 'run_id', 'text', 'created_at'],
                  properties: {
                    candidate_id: { bsonType: 'string' },
                    run_id: { bsonType: 'string' },
                    text: { bsonType: 'string' },
                    metrics: {
                      bsonType: 'object',
                      properties: { tokens_in: { bsonType: 'int' }, tokens_out: { bsonType: 'int' } }
                    },
                    created_at: { bsonType: 'date' },
                    selected: { bsonType: 'bool' }
                  }
                }
              },
              final_text: { bsonType: 'string' },
              selected_candidate_id: { bsonType: 'string' },
              tables: {
                bsonType: 'array',
                items: {
                  bsonType: 'object',
                  required: ['table_type', 'columns', 'rows', 'source'],
                  properties: {
                    table_type: { bsonType: 'string' },
                    columns: { bsonType: 'array', items: { bsonType: 'string' } },
                    rows: { bsonType: 'array', items: { bsonType: 'object' } },
                    source: { enum: ['postgres:sql', 'computed', 'manual'] }
                  }
                }
              },
              images: {
                bsonType: 'array',
                items: {
                  bsonType: 'object',
                  required: ['attachment_id'],
                  properties: {
                    attachment_id: { bsonType: 'string' },
                    caption: { bsonType: 'string' },
                    position: { bsonType: 'int' }
                  }
                }
              }
            },
            oneOf: [ { required: ['raw_text'] }, { required: ['edited_text'] } ]
          },
          sources: {
            bsonType: 'array',
            items: {
              bsonType: 'object',
              required: ['kb_source_id'],
              properties: {
                kb_source_id: { bsonType: 'string' },
                chunk_ids: { bsonType: 'array', items: { bsonType: 'string' } },
                citation_text: { bsonType: 'string' }
              }
            }
          },
          llm: {
            bsonType: 'object',
            properties: {
              provider_id: { bsonType: 'string' },
              model_id: { bsonType: 'string' },
              prompt: { bsonType: 'string' },
              parameters: {
                bsonType: 'object',
                properties: {
                  temperature: { bsonType: 'double' },
                  top_p: { bsonType: 'double' },
                  max_tokens: { bsonType: 'int' }
                }
              },
              tokens: { bsonType: 'object', properties: { input: { bsonType: 'int' }, output: { bsonType: 'int' } } },
              warnings: { bsonType: 'array', items: { bsonType: 'string' } }
            }
          },
          conversation_id: { bsonType: 'string' },
          audit: {
            bsonType: 'object',
            required: ['created_at', 'created_by'],
            properties: {
              created_at: { bsonType: 'date' },
              created_by: { bsonType: 'string' },
              updated_at: { bsonType: 'date' },
              updated_by: { bsonType: 'string' }
            }
          }
        }
      }
    },
    status: { enum: ['draft', 'final'] },
    audit: {
      bsonType: 'object',
      required: ['created_at', 'created_by'],
      properties: {
        created_at: { bsonType: 'date' },
        created_by: { bsonType: 'string' },
        updated_at: { bsonType: 'date' },
        updated_by: { bsonType: 'string' }
      }
    }
  }
});
DB.reports.createIndex({ activity_ids: 1 });
DB.reports.createIndex({ template_version_code: 1 });
DB.reports.createIndex({ 'sections.section_no': 1 });

ensureCollection('report_template_outline', {
  bsonType: 'object',
  required: ['template_version_code', 'outline'],
  properties: {
    template_version_code: { bsonType: 'string' },
    outline: {
      bsonType: 'array',
      minItems: 1,
      items: {
        bsonType: 'object',
        required: ['section_no', 'section_name', 'level', 'style', 'required'],
        properties: {
          section_no: { bsonType: 'string' },
          section_name: { bsonType: 'string' },
          level: { bsonType: 'int' },
          style: { bsonType: 'string' },
          required: { bsonType: 'bool' },
          default_binding: {
            bsonType: 'object',
            properties: {
              data_source: { enum: ['activity', 'events', 'evaluation', 'mix'] },
              indicator_scopes: {
                bsonType: 'object',
                properties: {
                  dimension_ids: { bsonType: 'array', items: { bsonType: 'string' } },
                  theme_ids: { bsonType: 'array', items: { bsonType: 'string' } }
                }
              },
              event_scopes: {
                bsonType: 'object',
                properties: {
                  types: { bsonType: 'array', items: { bsonType: 'string' } },
                  status: { bsonType: 'array', items: { bsonType: 'string' } }
                }
              },
              activity_scope: { enum: ['all', 'primary', 'custom'] }
            }
          },
          default_llm_model_code: { bsonType: 'string' }
        }
      }
    }
  }
});
DB.report_template_outline.createIndex({ template_version_code: 1 }, { unique: true });

ensureCollection('section_generation_runs', {
  bsonType: 'object',
  required: ['report_id', 'section_no', 'input_snapshot', 'prompt', 'llm_params', 'metrics', 'status', 'created_at'],
  properties: {
    report_id: { bsonType: 'string' },
    section_no: { bsonType: 'string' },
    conversation_id: { bsonType: 'string' },
    input_snapshot: { bsonType: 'object' },
    prompt: { bsonType: 'string' },
    llm_params: {
      bsonType: 'object',
      properties: {
        provider_id: { bsonType: 'string' },
        model_id: { bsonType: 'string' },
        temperature: { bsonType: 'double' },
        top_p: { bsonType: 'double' },
        max_tokens: { bsonType: 'int' }
      }
    },
    messages: {
      bsonType: 'array',
      items: { bsonType: 'object', properties: { role: { bsonType: 'string' }, content: { bsonType: 'string' }, created_at: { bsonType: 'date' }, model_id: { bsonType: 'string' } } }
    },
    output_text: { bsonType: 'string' },
    metrics: { bsonType: 'object', properties: { tokens_in: { bsonType: 'int' }, tokens_out: { bsonType: 'int' }, duration_ms: { bsonType: 'int' } } },
    parent_run_id: { bsonType: 'string' },
    selected_candidate_id: { bsonType: 'string' },
    status: { enum: ['success', 'failed'] },
    error: { bsonType: 'string' },
    created_at: { bsonType: 'date' },
    created_by: { bsonType: 'string' }
  }
});
DB.section_generation_runs.createIndex({ report_id: 1, section_no: 1, conversation_id: 1, created_at: -1 });

ensureCollection('section_conversations', {
  bsonType: 'object',
  required: ['report_id', 'section_no', 'conversation_id'],
  properties: {
    report_id: { bsonType: 'string' },
    section_no: { bsonType: 'string' },
    conversation_id: { bsonType: 'string' },
    messages: { bsonType: 'array', items: { bsonType: 'object', properties: { role: { bsonType: 'string' }, content: { bsonType: 'string' }, created_at: { bsonType: 'date' }, model_id: { bsonType: 'string' } }, required: ['role', 'content'] } },
    current_run_id: { bsonType: 'string' },
    status: { enum: ['active', 'closed'] },
    created_at: { bsonType: 'date' }
  }
});
DB.section_conversations.createIndex({ report_id: 1, section_no: 1, conversation_id: 1 });

print('Mongo collections updated: reports, report_template_outline, section_generation_runs, section_conversations');